<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--课程数据-->
      <el-col :span="24" :xs="24">
        <el-form :rules="queryForm" ref="queryForm" :model="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="queryForm.name" placeholder="请输入课程名称" clearable style="width: 240px" />
          </el-form-item>

          <el-form-item label="课程教练" prop="coach">
            <el-select clearable v-model="queryForm.coach" placeholder="请选择" style="width: 200px;">
              <el-option v-for="item in coachs" :key="item.coachName" :label="item.coachName" :value="item.coachName"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="Listload">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handelAdd">新增</el-button>
          </el-col>
        </el-row>

        <el-table :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="课程图片" align="center" prop="images">
            <template slot-scope="scope">
              <ImagePreview :src="String(scope.row.images)"></ImagePreview>
            </template>
          </el-table-column> 
          <el-table-column label="课程名称" align="center" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="课程类型" align="center" prop="courseType" />
          <el-table-column label="课程教练" align="center" prop="coach" ></el-table-column>
          <el-table-column label="课程难度" align="center" prop="difficulty" ></el-table-column>
          <el-table-column label="所属场馆" align="center" prop="venue" />
          <el-table-column label="课程时长" align="center" prop="courseTime">
            <template slot-scope="scope">
              {{ scope.row.courseTime + '小时' }}
            </template>
          </el-table-column>
          <el-table-column label="课程描述" align="center" prop="description" :show-overflow-tooltip="true" />
          <el-table-column label="可预约人数" align="center" prop="reservation" />
          <el-table-column label="课程状态" align="center" prop="status">
            <template slot-scope="scope">
                <!-- 假设 "0"、"1"、"2" 和 "3" 分别表示 "待预约"、"待训练"、"进行中" 和 "已完成" -->
              {{ getStatusLabel(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="开始时间" align="center" prop="startTime" />
          <el-table-column label="结束时间" align="center" prop="endTime" />
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handelEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="del(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryForm.pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :limit.sync="queryForm.pageSize"
      @pagination="Listload"
    />
      </el-col>
    </el-row>

    <!-- 添加或修改课程配置对话框 -->
    <el-dialog :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程图片" prop="images">
              <el-upload style=" margin-left: 13%" action="123123123" list-type="picture-card" class="upload-demo" :show-file-list="false" :before-upload="beforeAvatarUpload">
                <img height="148" v-if="images" :src="images" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!--  -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入课程名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程类型" prop="courseType">
              <el-select clearable v-model="form.courseType" placeholder="请选择课程类型" maxlength="50">
                <el-option v-for="item in fitness" :key="item.id" :label="item.fitnessPurposeName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--  -->

        <el-row>
          <el-col :span="12">
            <el-form-item label="课程难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择课程难度">
                <el-option label="零基础" value="零基础"></el-option>
                <el-option label="初学者" value="初学者"></el-option>
                <el-option label="入门" value="入门"></el-option>
                <el-option label="进阶" value="进阶"></el-option>
                <el-option label="专业" value="专业"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程教练" prop="coach">
              <el-select clearable v-model="form.coachId" placeholder="请选择课程教练" maxlength="50">
                <el-option v-for="item in coachs" :key="item.id" :label="item.coachName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--  -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                style="width: 200px;"
                v-model="form.startTime"
                type="datetime"
                placeholder="选择日期时间"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!--  -->
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                style="width: 200px;"
                v-model="form.endTime"
                type="datetime"
                placeholder="选择日期时间"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!--  -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="可约人数" prop="reservation">
              <el-input type="number" v-model="form.reservation" placeholder="请输入可约人数" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--  -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程描述">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveupdate">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { listCourse,addCourse,modify,delCourse,listvenue,listcoach,listfitness } from "@/api/course/course.js"; // 导入课程接口
import { list } from "@/api/monitor/logininfor";
import { param } from "@/utils";
import moment from 'moment';

export default {
  name: 'Course',
  data() {
    return {
      // 课程数据
      tableData: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      multipleSelection: [],
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 图片回显
      images: "",
      //添加时赋值
      addimages: "",
      // 表单参数
      form: {},
      // 场馆下拉框
      venues: [],
      // 教练下拉框
      coachs: [],
      // 课程类型下拉框
      fitness: [],
      // 课程查询条件
      queryForm: {
        pageNum: 1,
        pageSize: 5,
        name: '',
        coach: '',
        venueUniqueIdentifier: window.sessionStorage.getItem('venueUniqueIdentifier')
      },
      queryForms:{
        venueId: window.sessionStorage.getItem('venueUniqueIdentifier')
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入课程描述", trigger: "blur" },
        ],
        coachId: [
          { required: true, message: "请输入课程教练", trigger: "blur" },
        ],
        venue: [
          { required: true, message: "请输入所属场馆", trigger: "blur" },
        ],
        reservation: [
          { required: true, message: "请输入可约人数", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value <= 5) {
                callback(); // 验证通过
              } else {
                callback(new Error("不可超过5人"));
              }
            },
            trigger: "blur"
          }
        ],
        courseType: [
          { required: true, message: "请选择课程类型", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "blur" },
        ],
        difficulty: [
          { required: true, message: "请选择课程难度", trigger: "blur" },
        ],
      },
      //日期选择器 今天 昨天 一周前
      pickerOptions: {
        //禁用为过的日期
        // disabledDate(time) {
        //   return time.getTime() > Date.now();
        // },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        },{
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        },{
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      
    }
  },
  created() {
    this.Listload();
  },
  methods: {
    getStatusLabel(status) {
        switch (status) {
            case "0":
                return "待预约";
            case "1":
                return "待训练";
            case "2":
                return "进行中";
            case "3":
                return "已完成";
            default:
                return "";
        }
    },
    /** 计算时间差 */ 
    calculateTimeDiff(start, end) {
      const startTime = new Date(start);
      const endTime = new Date(end);
      return endTime - startTime; // 时间差（毫秒）
    },
    /** 格式化时长 */ 
    formatDuration(row) {
      const timeDiff = this.calculateTimeDiff(row.startTime, row.endTime);

      // 将毫秒转换为分钟
      const minutes = timeDiff / 1000 / 60;

      if (minutes >= 60) {
        // 如果时长大于或等于60分钟，以小时和分钟格式显示
        const hours = Math.floor(minutes / 60);
        const remainingMinutes = minutes % 60;

        if (remainingMinutes === 0) {
          return `${hours}小时`;
        } else {
          return `${hours}小时${remainingMinutes}分钟`;
        }
      } else {
        // 如果时长小于60分钟，以分钟格式显示
        return `${minutes}分钟`;
      }
    },
    /** 查询课程列表 */
    Listload() {
      listCourse(this.addDateRange(this.queryForm)).then(res => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
      listvenue().then(res => {
        this.venues = res.data;
      });
      listcoach(this.queryForms).then(res => {
        this.coachs = res.data;
      });
      listfitness().then(res => {
        this.fitness = res.data;
      });
    },
    /** 提交按钮（新增修改） */
    saveupdate() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = new FormData();
          // console.log(formData)
          // 格式化日期时间字段
          formData.set("startTime", moment(this.form.startTime).format("YYYY-MM-DD HH:mm"));
          formData.set("endTime", moment(this.form.endTime).format("YYYY-MM-DD HH:mm"));

          // 将其他表单数据添加到 formData 中
          for (const key in this.form) {
            if (key !== "startTime" && key !== "endTime") {
              formData.set(key, this.form[key]);
            }
          }
          if (this.addimages) {
            // console.log(this.addimages);
            formData.set("file", this.addimages, this.addimages.name);
          }
          formData.set("venueUniqueIdentifier", window.sessionStorage.getItem('venueUniqueIdentifier'))
          console.log(formData)
          addCourse(formData).then(res => {
            if (this.form.id != undefined) {
              this.$modal.msgSuccess("修改成功");
              this.images = "";
              this.addimages="";
              this.open = false;
              this.Listload();
            } else {
              this.$modal.msgSuccess("新增成功");
              this.images = "";
              this.addimages="";
              this.open = false;
              this.Listload();
            }
          });
        }
      });
    },
    /** 文件上传校验 */
    beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
      //赋值
      this.addimages = file;
      this.images = URL.createObjectURL(file);
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
    /** 添加弹窗 */
    handelAdd() {
      this.form = {}
      this.images ="";
      this.open = true;
    },
    /** 修改弹窗 */
    handelEdit(row) {
      this.form = {}
      this.form = JSON.parse(JSON.stringify(row))
      this.images = process.env.VUE_APP_IMG_BASE_URL +  row.images;
      this.open = true;
    },
    /** 删除按钮操作 */
    del(row) {
      // const courseIds = row.id || row.name;
      this.$modal.confirm('是否确认删除课程名称为"' + row.name + '"的数据项？').then(function() {
        return delCourse(row.id);
      }).then(() => {
        this.Listload();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 选中表格 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 重置查询条件 */
    reset() {
        this.queryForm.name = ""
        this.queryForm.coach = ""
        this.Listload()
    },
    /** 分页 */
    handleSizeChange(pageSize){
      console.log(pageSize);
      this.pageSize = pageSize;
      this.Listload();
    },
    handleCurrentChange(pageNum){
      console.log(pageNum);
      this.pageNum = pageNum;
      this.Listload();
    },
  },

}
</script>